package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.DishDao;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);
        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
//        flavors.stream().map((item)->{
//            item.setDishId();
//        })
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }

        dishFlavorService.saveBatch(flavors);
    }
//根据id查询菜品对应的信息
    public DishDto getByIdFlavor(Long id){
        Dish byId = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(byId,dishDto);
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();

        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,byId.getId());
        List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    //修改菜品信息
    @Transactional
    public void updatee(DishDto dishDto){
           this.updateById(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        Long id = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> dishFlavoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavoLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        dishFlavorService.remove(dishFlavoLambdaQueryWrapper);
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }
       dishFlavorService.saveBatch(flavors);

    }
}
